import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import { ConfigService } from '@nestjs/config';
import { DataSource, DataSourceOptions } from 'typeorm';
import * as path from 'path';

// 实体路径 - 使用共享实体库
const entitiesPath = path.join(__dirname, '../../../libs/entities/src/*.entity{.ts,.js}');

export const getDatabaseConfig = (configService: ConfigService): TypeOrmModuleOptions => {
    return {
        type: configService.get('DB_TYPE', 'mysql') as 'mysql',
        host: configService.get('ADMIN_DATABASE_HOST', 'localhost'),
        port: configService.get('ADMIN_DATABASE_PORT', 3306),
        username: configService.get('ADMIN_DATABASE_USER', 'root'),
        password: configService.get<string>('ADMIN_DATABASE_PASSWD', 'root'),
        database: configService.get<string>('ADMIN_DATABASE_TABLE', 'kv_blog'),
        entities: [entitiesPath],
        // synchronize: configService.get('ADMIN_DB_SYNC', true),
        synchronize: true,
        logging: configService.get('ADMIN_DB_LOGGING', false),
        timezone: '+08:00',
        charset: 'utf8mb4',
        extra: {
            charset: 'utf8mb4_unicode_ci',
            connectionLimit: 10,
        },
        // 迁移配置
        migrations: [path.join(__dirname, '../migrations/*{.ts,.js}')],
        migrationsTableName: 'migrations',
        migrationsRun: false,
    };
};

// 用于 CLI 命令的数据源配置
export const dataSourceOptions: DataSourceOptions = {
    type: 'mysql',
    host: process.env.ADMIN_DATABASE_HOST || 'localhost',
    port: parseInt(process.env.ADMIN_DATABASE_PORT) || 3306,
    username: process.env.ADMIN_DATABASE_USER || 'root',
    password: process.env.ADMIN_DATABASE_PASSWD || 'root',
    database: process.env.ADMIN_DATABASE_TABLE || 'kv_blog',
    entities: [entitiesPath],
    synchronize: false,
    migrations: [path.join(__dirname, '../migrations/*{.ts,.js}')],
    migrationsTableName: 'migrations',
};

const dataSource = new DataSource(dataSourceOptions);
export default dataSource;
